package com.tomtop.core.web.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.Netty4ClientHttpRequestFactory;

import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;

@Configuration
@ConditionalOnMissingBean(ClientHttpRequestFactory.class)
@ConditionalOnClass(NioEventLoopGroup.class)
@ConditionalOnMissingClass("org.apache.http.client.HttpClient")
public class Netty4RestTemplateConfig {
	
	@ConditionalOnMissingBean
	@Bean EventLoopGroup eventLoopGroup(){
		int ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2;
		NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(ioWorkerCount);
		eventLoopGroup.setIoRatio(50);
		return eventLoopGroup;
	}
	
	@Bean Netty4ClientHttpRequestFactory netty4ClientHttpRequestFactory(EventLoopGroup eventLoopGroup){
		Netty4ClientHttpRequestFactory netty4ClientHttpRequestFactory=new Netty4ClientHttpRequestFactory(eventLoopGroup);
		netty4ClientHttpRequestFactory.setConnectTimeout(8000);
		netty4ClientHttpRequestFactory.setMaxResponseSize(2000);
		netty4ClientHttpRequestFactory.setReadTimeout(1000);
		return netty4ClientHttpRequestFactory; 
	}
	
}
